import random

from django.shortcuts import render

# Create your views here.
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q
from rest_framework import viewsets, status,serializers,mixins
from rest_framework.mixins import CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication

from MxShop.settings import APIKEY
from rest_framework.response import Response
from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler

from users.models import VerifyCode
from users.serializers import SmsSerializer,UserRegisterSerializer,UserDetailSerializer
from utils.yunpian import YunPian

User = get_user_model()

class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """
    def authenticate(self,request, username=None, password=None, **kwargs):
        try:
            #用户名和手机都能登录
            user = User.objects.get(
                Q(username=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

class SmsCodeViewSet(CreateModelMixin,viewsets.GenericViewSet):

    # 指定序列化器
    serializer_class = SmsSerializer


    def generate_code(self):
        """
        生成四位数验证码
        :return:
        """
        sms_code = '%04d' % random.randint(0, 9999)
        return sms_code



    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        # 数据校验
        serializer.is_valid(raise_exception=True)
        mobile = serializer.validated_data['mobile']

        # 生成验证码
        code = self.generate_code()
        # 这里直接打印出来（别问，问就是贫穷限制了我。。。）
        print("=============================>本次的验证码是：",code)

        # 调用发送验证码接口
        # yunpian = YunPian(APIKEY)
        # sms_status = yunpian.send_sms(code,mobil)
        # if sms_status["code"] != 0:
        #     return Response({
        #         "mobile": sms_status["msg"]
        #     }, status=status.HTTP_400_BAD_REQUEST)
    # else:
        # 存入数据库返回响应
        code_record = VerifyCode(code=code, mobile=mobile)
        code_record.save()
        return Response({
            "mobile": mobile
        }, status=status.HTTP_201_CREATED)



class UserViewSet(CreateModelMixin,mixins.UpdateModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    """
    用户
    """
    serializer_class = UserRegisterSerializer
    queryset = User.objects.all()
    # 指定用户认证
    authentication_classes = [JSONWebTokenAuthentication,SessionAuthentication]


    def create(self, request, *args, **kwargs):
        """
        list:
            用户注册
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        # 重写create方法

        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)  # 获取token
        re_dict["name"] = user.name if user.name else user.username
        # 返回浏览器保存，不保存在服务器

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)


    def get_object(self):
        """
        返回user对象
        :return:
        """
        return self.request.user


    def perform_create(self, serializer):
        """
        调用序列化器的create方法
        :param serializer:
        :return:
        """
        return serializer.save()

    def get_permissions(self):
        """
        根据请求方式判断是否认证
        :return:
        """
        if self.action == "retrieve":
            # 用户中心需要认证
            return [IsAuthenticated()]
        elif self.action == "create":
            # 用户注册不需要认证
            return []
        return []


    def get_serializer_class(self):
        """
        根据请求类型指定序列化器
        :return:
        """
        if self.action == "retrieve":
            # 返回用户中心序列化器
            return UserDetailSerializer
        elif self.action == "create":
            # 返回用户注册序列化器
            return UserRegisterSerializer
        return UserDetailSerializer











